<template>
  <div v-loading="loading">
    <div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>亿码互联管理系统</el-breadcrumb-item>
        <el-breadcrumb-item> 我扫的码 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="mt-4">
      <el-table
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        :header-cell-style="{ background: 'rgba(251, 191, 36,1)', color: '#fff', fontWeight: 'bold' }"
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <!-- <el-table-column width="50">
          <template #default="scope">
            <div class="text-center">
              <div
                style="
                  width: 20px;
                  height: 20px;
                  margin-left: 10px;
                  line-height: 20px;
                  background: #ccc;
                  border-radius: 50%;
                "
              >
                {{ scope.$index + 1 }}
              </div>
            </div>
          </template>
        </el-table-column> -->
        <!-- <el-table-column width="60">
          <template #default="scope">
            <div v-if="parseJson(scope.row.eqJson)">
              <el-tag type="primary" v-if="scope.row.eqType === 0" effect="dark">图文</el-tag>
              <el-tag type="danger" v-if="scope.row.eqType === 1" effect="dark">表单</el-tag>
              <el-tag type="success" v-if="scope.row.eqType === 2" effect="dark">名片</el-tag>
            </div>
            <div v-else>
              <el-tag type="warning" effect="dark">新版</el-tag>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="二维码" width="150" header-align="center">
          <template #default="scope">
            <img :src="scope.row.eqUrl" class="h-20 w-20" style="margin: 0 auto" @click="openImg(scope.row)" />
          </template>
        </el-table-column>

        <el-table-column label="标题">
          <template #default="scope">
            <div>
              {{ scope.row.eqTitle }}
            </div>

            <el-text class="mx-1" size="small" v-if="scope.row.template"
              ><el-icon> <Platform /> </el-icon
              >{{ scope.row.template ? '[' + JSON.parse(scope.row.template).tName + ']' : '' }}</el-text
            >
          </template>
        </el-table-column>

        <el-table-column label="查看时间" width="250">
          <template #default="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250">
          <template #default="scope">
            <!-- <el-tooltip class="box-item" effect="dark" content="预览">
              <el-button type="primary" :icon="View" circle @click="view(scope.row)" />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="修改二维码">
              <el-button type="success" :icon="Edit" circle @click="edit(scope.row)" />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除二维码">
              <el-button type="danger" :icon="Delete" circle @click="del(scope.row)" />
            </el-tooltip>-->
            <el-tooltip class="box-item" effect="dark" content="扫描记录">
              <el-button type="info" :icon="List" circle @click="openitem2(scope.row)" />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="扫描数据">
              <el-button type="info" :icon="Message" circle @click="openitem(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-2"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 15, 20, 50]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <el-dialog v-model="dialogVisible2" width="500">
        <div class="m-1 h-170">
          <div class="device iphone-x">
            <!--    外部轮廓    -->
            <div class="frame">
              <div class="content p-1">
                <preview :title="title" />
              </div>
            </div>

            <!--    天线    -->
            <div class="stripe"></div>

            <!--    听筒孔    -->
            <div class="header">
              <div class="sensors"></div>
            </div>

            <!--    按键    -->
            <div class="btns"></div>
            <div class="power"></div>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible2 = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogVisible3" width="560" hend>
        <div style="height: 600px; overflow: scroll">
          <el-table
            :data="list3"
            :header-cell-style="{ background: 'rgba(251, 191, 36,1)', color: '#fff', fontWeight: 'bold' }"
            row-key="id"
            style="width: 100%"
            default-expand-all
          >
            <el-table-column width="150">
              <template #default="scope">
                <img :src="scope.row.uAvatar" class="h-10 w-10" style="margin: 0 auto; border-radius: 50%" />
              </template>
            </el-table-column>
            <el-table-column prop="uNickname" label="用户" width="180" />
            <el-table-column prop="createdTime" label="扫描时间" width="180" />
            <!-- <el-table-column width="150">
              <template #default="scope">
                {{ scope.row.items && scope.row.items.length }}
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-tooltip v-if="scope.row.eqType === 1" class="box-item" effect="dark" content="预览">
                  <el-button type="primary" :icon="View" circle @click="view2(scope.row)" />
                </el-tooltip>
              </template>
            </el-table-column> -->
          </el-table>
          <!-- <el-pagination
            class="mt-2"
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            :page-sizes="[7, 10, 15, 20, 50]"
            :page-size="pagesize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total2"
          >
          </el-pagination> -->
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible3 = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogVisible4" width="800" hend>
        <div class="h-80" style="overflow: auto">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane v-for="(o, i) in rr" :key="i" :label="o.time" :name="o.time">
              <div>
                <el-row class="border" v-for="(item, index) in o.data" :key="index">
                  <el-col :span="8">
                    <div class="name">
                      <div class="ml-10" style="padding: 20px; white-space: nowrap">{{ item.title }}:</div>
                    </div>
                  </el-col>
                  <el-col :span="16">
                    <div class="" style="padding: 20px; white-space: nowrap">
                      <div v-if="checkFileType(item.value) === 'image'" style="width: 100%; word-wrap: break-word">
                        <img
                          v-show="item.value"
                          :src="item.value"
                          class="aspect-16/9"
                          style="width: 80%; margin: 0 auto; margin-top: 30rpx"
                          @click="clickImg(item.value)"
                        />
                      </div>
                      <div v-else-if="checkFileType(item.value) === 'video'" style="width: 100%; word-wrap: break-word">
                        <video
                          v-show="item.value"
                          :src="item.value"
                          mode="widthFix"
                          class="aspect-16/9"
                          controls
                        ></video>
                      </div>
                      <div v-else-if="item.type === '检查项'" style="width: 100%; word-wrap: break-word">
                        <div v-for="(o, i) in item.data.list" :key="i">
                          {{ o.title }} -> {{ item.value[i] === 1 ? '通过' : '未通过' }}
                          <br />
                        </div>
                      </div>
                      <div v-else-if="item.type === '地址'" style="width: 100%; word-wrap: break-word">
                        {{ item.data.city }}- {{ item.data.address }}
                      </div>
                      <div v-else-if="item.type === '表格'" style="width: 100%; word-wrap: break-word"></div>
                      <div v-else-if="item.type === '自增表格'" style="width: 100%; word-wrap: break-word">
                        <table border stripe empty-text="暂无更多数据">
                          <tr v-for="o2 in item.data.table" :key="o2">
                            <td align="center">
                              {{ o2.th }}
                            </td>
                            <td align="center">
                              {{ o2.td }}
                            </td>
                          </tr>
                        </table>
                      </div>
                      <div v-else-if="item.type === 'NPS量表'" style="width: 100%; word-wrap: break-word">
                        <div v-for="i in 11" :key="i">
                          <div
                            class="float-left ml-1 border-1 p-1 px-1"
                            :class="i - 1 < parseInt(item.value) ? 'bg-blue-500 text-white' : ''"
                          >
                            {{ i - 1 }}
                          </div>
                        </div>
                      </div>
                      <div v-else-if="item.type === '评价'" style="width: 100%; word-wrap: break-word">
                        <el-rate
                          v-model="item.value"
                          active-color="#fcca00"
                          :count="item.data.count"
                          readonly
                        ></el-rate>
                      </div>
                      <div v-else style="width: 100%; word-wrap: break-word">
                        {{ item.value }}
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible4 = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog title v-model="isShow" @close="closeDialog">
        <video
          :src="videoUrl"
          controls
          autoplay
          class="video"
          style="width: auto; height: 500px; margin: 0 auto"
        ></video>
      </el-dialog>
      <el-dialog class="no-header-dialog" v-model="perviewdialogVisible" title="二维码预览" width="400">
        <div class="relative" style="height: 720px">
          <div class="absolute top-0 right-0 cursor-pointer" @click="perviewdialogVisible = false">
            <el-icon color="#fff" size="20"><CircleClose /></el-icon>
          </div>
          <perview :list="list2" :title="title" />
          <div style="clear: both"></div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { delQrcode, getQrcode, eqrecord_list, i12_template_one, getQrcodebyid } from '@/api/index.js';
import perview from '@/views/editor/components/preview.vue';
import { View, List, Delete, Edit, Message, Search, Star } from '@element-plus/icons-vue';
const showToast = inject('showToast');
const router = useRouter();
const loading = ref(true);
const isShow = ref(false);
loading.value = false;
const currentPage = ref(1);
const pagesize = ref(5);
const total = ref(0);
const currentPage2 = ref(1);
const pagesize2 = ref(5);
const total2 = ref(0);

const currentPage3 = ref(1);
const pagesize3 = ref(7);
const total3 = ref(0);

const list = ref([]);
const list3 = ref([]);
const title = ref('');
const videoUrl = ref('');
const dialogVisible2 = ref(false);
const dialogVisible3 = ref(false);
const dialogVisible4 = ref(false);
const eqlist = ref([]);
import { useListStore } from '@/stores/list';
const user = JSON.parse(localStorage.getItem('userinfo'));
const listStore = useListStore();
var l = listStore.list;
const perviewdialogVisible = ref(false);
function parseJson(json) {
  let list = JSON.parse(json);
  // console.log(this.list.hasOwnProperty('mdata'), this.list.hasOwnProperty('fdata'), this.card !== {})
  // 判断json中有没有mdata 或者 fdata
  if (list.hasOwnProperty('mdata') || list.hasOwnProperty('fdata') || list.hasOwnProperty('avatar')) {
    return true;
  } else {
    return false;
  }
}
const list2 = ref([]);
const rr = ref([]);

//const title = ref('')
function openImg(o) {
  console.log('o', o);
  ElMessageBox.alert(
    '<div class="w-full text-center"><img src="' +
      o.eqUrl +
      '"  style="margin: 0 aut;width:360px;height:360px;margin-left:20px"/></div>',
    o.eqTitle,
    {
      dangerouslyUseHTMLString: true,
    },
  );
}
function checkFileType(fileName) {
  console.log('fileName', fileName);
  // 确保 fileName 是字符串
  if (typeof fileName !== 'string') {
    return undefined;
  }

  // 使用正则表达式匹配文件扩展名
  const extensionMatch = fileName.match(/\.(\w+)$/);
  if (!extensionMatch) return undefined;

  const extension = extensionMatch[1].toLowerCase();

  // 定义视频和图片的扩展名列表
  const videoExtensions = ['mp4', 'avi', 'mov', 'mkv'];
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif'];

  // 检查扩展名是否为视频或图片
  return videoExtensions.includes(extension) ? 'video' : imageExtensions.includes(extension) ? 'image' : undefined;
}
const activeName = ref('');
function openitem2(item) {
  console.log('item', item);

  eqrecord_list({ eqId: item.eqId, scanUserid: user.id }).then((res) => {
    console.log('res:', res);
    list3.value = res.data.data.listdata;
    dialogVisible3.value = true;
  });
}
function openitem(item) {
  console.log('item', item);
  getQrcodebyid(item.eqId).then((res) => {
    console.log('res:', res);
    this.recordJson = [];
    const itm = res.data.data.onedata;

    console.log('itm:', itm);

    const data = JSON.parse(itm.eqJson);
    console.log('data:', data);
    let f = false;
    if (data.hasOwnProperty('mdata') || data.hasOwnProperty('fdata')) {
      f =
        data.fdata.filter(
          (itm) =>
            (itm.key === '基础表单' || itm.key === '个人信息') &&
            itm.item.title !== '表格' &&
            itm.item.title !== '分组标题' &&
            itm.item.title !== '名片',
        ).length > 0;
    } else {
      f =
        data.filter(
          (itm) =>
            (itm.key === '基础表单' || itm.key === '个人信息') &&
            itm.item.title !== '表格' &&
            itm.item.title !== '分组标题' &&
            itm.item.title !== '名片',
        ).length > 0;
    }

    if (itm.eqType === 1 && f) {
      eqrecord_list({ eqId: item.eqId, scanUserid: user.id }).then((res) => {
        console.log('res:', res);
        console.log(' res.data.data.formdata_list:', res.data.data.formdata_list);
        res.data.data.formdata_list.forEach((d, i) => {
          console.log('d:', d);
          const data = JSON.parse(d.recordJson);
          const r = [];
          if (data.hasOwnProperty('mdata') || data.hasOwnProperty('fdata')) {
            for (const key in data.fdata) {
              if (data.fdata.hasOwnProperty(key)) {
                if (
                  data.fdata[key].item.title !== '分组标题' &&
                  data.fdata[key].item.title !== '表格' &&
                  data.fdata[key].item.title !== '名片'
                ) {
                  r.push({
                    title: data.fdata[key].item.name,
                    value: data.fdata[key].item.value,
                    type: data.fdata[key].item.title,
                    data: data.fdata[key].item,
                  });
                }
              }
            }
          } else {
            for (const key in data) {
              console.log('key:', key);
              if (data.hasOwnProperty(key)) {
                if (
                  data[key].item &&
                  data[key].item.title !== '分组标题' &&
                  data[key].item.title !== '表格' &&
                  data[key].item.title !== '名片'
                ) {
                  r.push({
                    title: data[key].item.name,
                    value: data[key].item.value,
                    type: data[key].item.title,
                    data: data[key].item,
                  });
                }
              }
            }
          }
          rr.value.push({ time: d.updateTime, data: r, jsondata: data });
        });

        recordJson.value = rr.value[rr.value.length - 1].data;
        activeName.value = rr.value[rr.value.length - 1].time;
        console.log('recordJson.value:', rr.value);
        dialogVisible4.value = true;
        //this.$refs.popup.open('bottom');
      });
    } else {
      //this.previews(item.eqId);
      ElMessage({
        message: '该二维码不是表单类型',
        type: 'info',
      });
    }
    // if (itm.eqType === 1 && f) {
    //   if (data.hasOwnProperty('mdata') || data.hasOwnProperty('fdata')) {
    //     for (const key in data.fdata) {
    //       if (data.fdata.hasOwnProperty(key)) {
    //         if (data.fdata[key].item.title !== '分组标题' && data.fdata[key].item.title !== '表格' && data.fdata[key].item.title !== '名片') {
    //           this.recordJson.push({ title: data.fdata[key].item.name, value: data.fdata[key].item.value, type: data.fdata[key].item.title, data: data.fdata[key].item })
    //         }
    //       }
    //     }
    //   }
    //   else {
    //     console.log('!!!!!!!:')
    //     eqrecord_list({ eqId: item.eqId }).then((res) => {
    //       console.log('res:', res)
    //     })

    //     for (const key in data) {
    //       console.log('key:', key)
    //       if (data.hasOwnProperty(key)) {
    //         if (data[key].item && data[key].item.title !== '分组标题' && data[key].item.title !== '表格' && data[key].item.title !== '名片') {
    //           this.recordJson.push({ title: data[key].item.name, value: data[key].item.value, type: data[key].item.title, data: data[key].item })
    //         }
    //       }
    //     }
    //   }
    //   console.log('item', this.recordJson)
    //   this.$refs.popup.open('bottom')
    // }
    // else {
    // //  this.previews(item.eqId)
    // }
  });
}
function view(o) {
  list2.value = [];
  title.value = o.eqTitle;
  console.log(' title.value:', title.value);
  console.log('listStore.list', l);

  list2.value = JSON.parse(o.eqJson);
  console.log('list2.value:', list2.value);

  perviewdialogVisible.value = true;
}
function view2(o) {
  title.value = o.eqTitle === '' ? '电子名片' : o.eqTitle;
  console.log('listStore.list', l);
  if (o.eqType === 2) {
    var d = {
      mdata: [],
      fdata: [],
      card: JSON.parse(o.recordJson),
    };
    listStore.setList(d);
  } else {
    console.log('o', l);
    // l.mdata = JSON.parse(o.eqJson).mdata;
    // l.fdata = JSON.parse(o.eqJson).fdata;
    listStore.setList(JSON.parse(o.recordJson));
  }

  dialogVisible2.value = true;
}
function getvalue(i, key) {
  // console.log('eqlist2.value', eqlist2.value)
  const data = JSON.parse(eqlist2.value[i].recordJson);
  for (const key2 in data) {
    if (data.hasOwnProperty(key2)) {
      if (data[key2].item.name == key) {
        return data[key2].item.value;
      }
    }
  }
}
function getvalue2(i, key) {
  // console.log('eqlist2.value', eqlist2.value)
  const data = JSON.parse(eqlist2.value[i].recordJson);
  for (const key2 in data) {
    if (data.hasOwnProperty(key2)) {
      if (data[key2].item.name == key) {
        return data[key2].item.list;
      }
    }
  }
}
function getData() {
  eqrecord_list({}).then((res) => {
    list.value = res.data.data.listdata;
    // this.formdata_list = res.data.formdata_list;

    list.value.forEach((item) => {
      if (item.eqType === 2) {
        // getQrcodebyid(item.eqId).then((res) => {
        //   const j = JSON.parse(res.data.onedata.eqJson)

        //   item.eqTitle = `${j.name}的电子名片`
        // })
        if (!item.eqTitle) {
          item.eqTitle = `电子名片`;
        }
      }
    });
    //this.loading = false;
    //console.log('this.list', this.list);
    total.value = res.data.data.listdata.length;
  });
}
function extractImageValues(items) {
  const imageValues = []; // 用于存储"上传图片"的value集合

  items.forEach((item) => {
    if (item.key === '多媒体类' && item.item.title === '上传图片') {
      // 检查类别是"多媒体类"且标题是"上传图片"，然后将value添加到数组
      imageValues.push(item.item.value);
    }
  });

  return imageValues;
}
function playVideo(url) {
  console.log('url', url);
  isShow.value = true;
  // 将接受的值赋值给src
  videoUrl.value = url;
}
function closeDialog() {
  // 关闭弹框
  isShow.value = false;
  videoUrl.value = ''; // 清空数据 关闭视频播放
}

const eqlist2 = ref([]);
const recordJson = ref([]);
const imglist = ref([]);
function getlog(o) {
  eqrecord_list({
    eqId: o.id,
  }).then((res) => {
    eqlist.value = groupBy(res.data.data.listdata, 'uNickname');
    console.log('eqlist.value', eqlist.value);
    total2.value = eqlist.value.length;
    dialogVisible3.value = true;
  });
}
function groupBy(array, key) {
  const grouped = array.reduce((result, item) => {
    const groupKey = item[key];
    const groupItem = result[groupKey] || {
      id: new Date().getTime(),
      uNickname: item.uNickname,
      uAvatar: item.uAvatar,
      createdTime: item.createdTime,
      eqType: item.eqType,
      // hasChildren: false,
      items: [],
    };
    groupItem.items.push({
      id: item.id,
      uNickname: item.uNickname,
      uAvatar: item.uAvatar,
      createdTime: item.createdTime,

      recordJson: item.recordJson,
      value: item.value,
    });
    if (groupItem.items.length > 1) {
      groupItem.hasChildren = true;
    } else {
      groupItem.hasChildren = false;
    }
    result[groupKey] = groupItem;
    return result;
  }, {});

  // 将分组结果转换为数组
  return Object.values(grouped);
}

function getlog2(o) {
  eqrecord_list({
    eqId: o.id,
  }).then((res) => {
    eqlist2.value = res.data.data.formdata_list;
    //console.log('eqlist.value', eqlist2.value)
    total3.value = eqlist2.value.length;
    dialogVisible4.value = true;

    if (o.eqType === 1) {
      const data = JSON.parse(eqlist2.value[0].recordJson);
      console.log('data', data);
      for (const key in data) {
        // if (data.fdata.hasOwnProperty(key)) {
        recordJson.value.push({ title: data[key].item.name, type: data[key].item.title });
        // }
      }
      console.log('recordJson.value', recordJson.value);
    }
    console.log('eqlist2.value:', eqlist2.value);
    //遍历eqlist2.value

    eqlist2.value.forEach((item) => {
      console.log('item:', item.recordJson);
      const data = JSON.parse(item.recordJson);
      var c = extractImageValues(data);
      console.log('c:', c);
      imglist.value = [...imglist.value, ...c];
    });
    console.log('imglist.value', imglist.value);
  });
}
const tableRowClassName = ({ row, rowIndex }) => {
  //
  // if (parseJson(row.eqJson)) {
  //   if (row.eqType === 0) {
  //     return 'primary-row';
  //   } else if (row.eqType === 1) {
  //     return 'danger-row';
  //   } else if (row.eqType === 2) {
  //     return 'success-row';
  //   }
  // } else {
  //   return 'warning-row';
  // }
  return '';
};
function handleSizeChange(val) {
  pagesize.value = val;
}
function handleCurrentChange(val) {
  currentPage.value = val;
}
function handleSizeChange2(val) {
  pagesize2.value = val;
}
function handleCurrentChange2(val) {
  currentPage2.value = val;
}
function handleSizeChange3(val) {
  pagesize3.value = val;
}
function handleCurrentChange3(val) {
  currentPage3.value = val;
}
const edit = (o) => {
  //跳转路由 v3
  router.push('/v3?id=' + o.id);
};
const del = (o) => {
  ElMessageBox.confirm(`您确定要删除` + (o.eqTitle === '' ? '电子名片' : o.eqTitle) + `吗?`, '删除提示', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning',
  })
    .then(() => {
      delQrcode(o).then((res) => {
        getData();
      });
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    });
};
onMounted(() => {
  getData();
});
</script>
<style lang="less">
.no-header-dialog {
  background: transparent !important;
  box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0), 0px 8px 20px rgba(0, 0, 0, 0);
}

.no-header-dialog .el-dialog__header {
  display: none;
}
.el-table .primary-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
}

.el-table .danger-row {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
</style>

